const mockDatabase = require('../config/mockDatabase');
const { v4: uuidv4 } = require('uuid');

class ReportSubscription {
  constructor(data) {
    this.id = data.id;
    this.subscription_id = data.subscription_id;
    this.report_key = data.report_key;
    this.admin_id = data.admin_id;
    this.subscription_name = data.subscription_name;
    this.email_recipients = data.email_recipients;
    this.schedule_type = data.schedule_type;
    this.schedule_time = data.schedule_time;
    this.schedule_day = data.schedule_day;
    this.filters = data.filters;
    this.export_format = data.export_format;
    this.is_active = data.is_active;
    this.last_sent_at = data.last_sent_at;
    this.next_send_at = data.next_send_at;
    this.created_at = data.created_at;
    this.updated_at = data.updated_at;
  }

  // 创建新的订阅
  static async create(subscriptionData) {
    try {
      if (!mockDatabase.reportSubscriptions) {
        mockDatabase.reportSubscriptions = [];
      }
      
      const subscriptionId = uuidv4();
      const nextSendAt = this.calculateNextSendTime(
        subscriptionData.schedule_type,
        subscriptionData.schedule_time,
        subscriptionData.schedule_day
      );
      
      const newSubscription = {
        id: mockDatabase.reportSubscriptions.length + 1,
        subscription_id: subscriptionId,
        report_key: subscriptionData.report_key,
        admin_id: subscriptionData.admin_id,
        subscription_name: subscriptionData.subscription_name,
        email_recipients: subscriptionData.email_recipients,
        schedule_type: subscriptionData.schedule_type,
        schedule_time: subscriptionData.schedule_time,
        schedule_day: subscriptionData.schedule_day,
        filters: subscriptionData.filters || {},
        export_format: subscriptionData.export_format || 'xlsx',
        is_active: subscriptionData.is_active !== false,
        last_sent_at: null,
        next_send_at: nextSendAt.toISOString(),
        created_at: new Date().toISOString(),
        updated_at: new Date().toISOString()
      };
      
      mockDatabase.reportSubscriptions.push(newSubscription);
      return new ReportSubscription(newSubscription);
    } catch (error) {
      console.error('Error creating report subscription:', error);
      throw error;
    }
  }

  // 根据subscription_id获取订阅
  static async findBySubscriptionId(subscriptionId) {
    try {
      const subscriptions = mockDatabase.reportSubscriptions || [];
      const subscription = subscriptions.find(s => s.subscription_id === subscriptionId);
      
      return subscription ? new ReportSubscription(subscription) : null;
    } catch (error) {
      console.error('Error finding subscription by ID:', error);
      throw error;
    }
  }

  // 获取用户的订阅列表
  static async findByAdminId(adminId) {
    try {
      const subscriptions = mockDatabase.reportSubscriptions || [];
      const userSubscriptions = subscriptions
        .filter(s => s.admin_id === adminId)
        .sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
      
      return userSubscriptions.map(subscription => new ReportSubscription(subscription));
    } catch (error) {
      console.error('Error finding subscriptions by admin ID:', error);
      throw error;
    }
  }

  // 获取报表的订阅列表
  static async findByReportKey(reportKey) {
    try {
      const subscriptions = mockDatabase.reportSubscriptions || [];
      const reportSubscriptions = subscriptions
        .filter(s => s.report_key === reportKey && s.is_active)
        .sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
      
      return reportSubscriptions.map(subscription => new ReportSubscription(subscription));
    } catch (error) {
      console.error('Error finding subscriptions by report key:', error);
      throw error;
    }
  }

  // 获取需要发送的订阅
  static async findPendingSubscriptions() {
    try {
      const subscriptions = mockDatabase.reportSubscriptions || [];
      const now = new Date();
      
      const pendingSubscriptions = subscriptions.filter(s => 
        s.is_active && 
        s.next_send_at && 
        new Date(s.next_send_at) <= now
      );
      
      return pendingSubscriptions.map(subscription => new ReportSubscription(subscription));
    } catch (error) {
      console.error('Error finding pending subscriptions:', error);
      throw error;
    }
  }

  // 更新订阅
  static async update(subscriptionId, updateData) {
    try {
      const subscriptions = mockDatabase.reportSubscriptions || [];
      const subscriptionIndex = subscriptions.findIndex(s => s.subscription_id === subscriptionId);
      
      if (subscriptionIndex === -1) {
        throw new Error('Subscription not found');
      }
      
      // 如果更新了调度信息，重新计算下次发送时间
      if (updateData.schedule_type || updateData.schedule_time || updateData.schedule_day) {
        const subscription = subscriptions[subscriptionIndex];
        const nextSendAt = this.calculateNextSendTime(
          updateData.schedule_type || subscription.schedule_type,
          updateData.schedule_time || subscription.schedule_time,
          updateData.schedule_day || subscription.schedule_day
        );
        updateData.next_send_at = nextSendAt.toISOString();
      }
      
      subscriptions[subscriptionIndex] = {
        ...subscriptions[subscriptionIndex],
        ...updateData,
        updated_at: new Date().toISOString()
      };
      
      return new ReportSubscription(subscriptions[subscriptionIndex]);
    } catch (error) {
      console.error('Error updating subscription:', error);
      throw error;
    }
  }

  // 标记订阅已发送
  static async markSent(subscriptionId) {
    try {
      const subscriptions = mockDatabase.reportSubscriptions || [];
      const subscriptionIndex = subscriptions.findIndex(s => s.subscription_id === subscriptionId);
      
      if (subscriptionIndex === -1) {
        throw new Error('Subscription not found');
      }
      
      const subscription = subscriptions[subscriptionIndex];
      const nextSendAt = this.calculateNextSendTime(
        subscription.schedule_type,
        subscription.schedule_time,
        subscription.schedule_day
      );
      
      subscriptions[subscriptionIndex] = {
        ...subscription,
        last_sent_at: new Date().toISOString(),
        next_send_at: nextSendAt.toISOString(),
        updated_at: new Date().toISOString()
      };
      
      return new ReportSubscription(subscriptions[subscriptionIndex]);
    } catch (error) {
      console.error('Error marking subscription sent:', error);
      throw error;
    }
  }

  // 删除订阅
  static async delete(subscriptionId) {
    try {
      const subscriptions = mockDatabase.reportSubscriptions || [];
      const subscriptionIndex = subscriptions.findIndex(s => s.subscription_id === subscriptionId);
      
      if (subscriptionIndex === -1) {
        throw new Error('Subscription not found');
      }
      
      subscriptions.splice(subscriptionIndex, 1);
      return true;
    } catch (error) {
      console.error('Error deleting subscription:', error);
      throw error;
    }
  }

  // 启用/禁用订阅
  static async toggleActive(subscriptionId, isActive) {
    try {
      return await this.update(subscriptionId, { is_active: isActive });
    } catch (error) {
      console.error('Error toggling subscription active status:', error);
      throw error;
    }
  }

  // 计算下次发送时间
  static calculateNextSendTime(scheduleType, scheduleTime, scheduleDay = null) {
    const now = new Date();
    const [hours, minutes] = scheduleTime.split(':').map(Number);
    
    let nextSend = new Date();
    nextSend.setHours(hours, minutes, 0, 0);
    
    switch (scheduleType) {
      case 'daily':
        // 如果今天的时间已过，设置为明天
        if (nextSend <= now) {
          nextSend.setDate(nextSend.getDate() + 1);
        }
        break;
        
      case 'weekly':
        // scheduleDay: 0=周日, 1=周一, ..., 6=周六
        const targetDay = scheduleDay || 1; // 默认周一
        const currentDay = nextSend.getDay();
        let daysUntilTarget = targetDay - currentDay;
        
        if (daysUntilTarget < 0 || (daysUntilTarget === 0 && nextSend <= now)) {
          daysUntilTarget += 7;
        }
        
        nextSend.setDate(nextSend.getDate() + daysUntilTarget);
        break;
        
      case 'monthly':
        // scheduleDay: 1-31 表示每月的第几天
        const targetDate = scheduleDay || 1; // 默认每月1号
        nextSend.setDate(targetDate);
        
        // 如果这个月的日期已过，设置为下个月
        if (nextSend <= now) {
          nextSend.setMonth(nextSend.getMonth() + 1);
          nextSend.setDate(targetDate);
        }
        break;
        
      default:
        throw new Error('Invalid schedule type');
    }
    
    return nextSend;
  }

  // 获取订阅统计信息
  static async getSubscriptionStats(adminId = null, reportKey = null) {
    try {
      let subscriptions = mockDatabase.reportSubscriptions || [];
      
      // 应用筛选条件
      if (adminId) {
        subscriptions = subscriptions.filter(s => s.admin_id === adminId);
      }
      
      if (reportKey) {
        subscriptions = subscriptions.filter(s => s.report_key === reportKey);
      }
      
      const stats = {
        total: subscriptions.length,
        active: subscriptions.filter(s => s.is_active).length,
        inactive: subscriptions.filter(s => !s.is_active).length,
        schedule_types: {
          daily: subscriptions.filter(s => s.schedule_type === 'daily').length,
          weekly: subscriptions.filter(s => s.schedule_type === 'weekly').length,
          monthly: subscriptions.filter(s => s.schedule_type === 'monthly').length
        },
        formats: {
          csv: subscriptions.filter(s => s.export_format === 'csv').length,
          xlsx: subscriptions.filter(s => s.export_format === 'xlsx').length,
          pdf: subscriptions.filter(s => s.export_format === 'pdf').length
        }
      };
      
      return stats;
    } catch (error) {
      console.error('Error getting subscription stats:', error);
      throw error;
    }
  }

  // 验证订阅数据
  static validateSubscriptionData(subscriptionData) {
    const errors = [];
    
    if (!subscriptionData.report_key) {
      errors.push('report_key is required');
    }
    
    if (!subscriptionData.admin_id) {
      errors.push('admin_id is required');
    }
    
    if (!subscriptionData.subscription_name) {
      errors.push('subscription_name is required');
    }
    
    if (!subscriptionData.email_recipients || !Array.isArray(subscriptionData.email_recipients) || subscriptionData.email_recipients.length === 0) {
      errors.push('email_recipients must be a non-empty array');
    }
    
    if (!subscriptionData.schedule_type || !['daily', 'weekly', 'monthly'].includes(subscriptionData.schedule_type)) {
      errors.push('Valid schedule_type is required');
    }
    
    if (!subscriptionData.schedule_time || !/^\d{2}:\d{2}$/.test(subscriptionData.schedule_time)) {
      errors.push('schedule_time must be in HH:MM format');
    }
    
    if (subscriptionData.schedule_type === 'weekly' && (subscriptionData.schedule_day < 0 || subscriptionData.schedule_day > 6)) {
      errors.push('schedule_day for weekly must be 0-6');
    }
    
    if (subscriptionData.schedule_type === 'monthly' && (subscriptionData.schedule_day < 1 || subscriptionData.schedule_day > 31)) {
      errors.push('schedule_day for monthly must be 1-31');
    }
    
    if (subscriptionData.export_format && !['csv', 'xlsx', 'pdf'].includes(subscriptionData.export_format)) {
      errors.push('Valid export_format is required');
    }
    
    return errors;
  }
}

module.exports = ReportSubscription;